//
//  LoginViewController.m
//  OfficeBook
//
//  Created by 朱 琳 on 15/10/8.
//  Copyright (c) 2015年 sunny. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginUserNameViewCell.h"
#import "LoginPasswordViewCell.h"
#import "BookingViewController.h"
#import "UserModel.h"

NSString * const kLoginUserNameViewCell = @"LoginUserNameViewCell";
NSString * const kLoginPasswordViewCell = @"LoginPasswordViewCell";

@interface LoginViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"Sign in to Just Meeting";

    // close btn
//    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    closeBtn.frame = CGRectMake(0, 0, 44, 44);
//    closeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    [closeBtn setTitle:@"Close" forState:UIControlStateNormal];
//    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    closeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//    [closeBtn addTarget:self action:@selector(dismissVC) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *backBarItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
//    self.navigationItem.leftBarButtonItem = backBarItem;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#ebebeb"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //table footer
    [self initTableFooterView];
    
    [self.tableView registerClass:[LoginUserNameViewCell class] forCellReuseIdentifier:kLoginUserNameViewCell];
    [self.tableView registerClass:[LoginPasswordViewCell class] forCellReuseIdentifier:kLoginPasswordViewCell];
    
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [(UITextField *)[self.tableView viewWithTag:LoginUserNameCellTextFieldTag] becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0: {
            LoginUserNameViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kLoginUserNameViewCell forIndexPath:indexPath];
            return cell;
            break;
        }
        case 1: {
            LoginPasswordViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kLoginPasswordViewCell forIndexPath:indexPath];
            return cell;
            break;
        }
        default:
            return nil;
            break;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 18.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}


#pragma mark - login/register

-(void)loginAccount:(UIButton *)sender {
    LoginUserNameViewCell *userCell = (LoginUserNameViewCell*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    LoginPasswordViewCell *pwdCell = (LoginPasswordViewCell*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    NSLog(@"username:%@ pwd:%@", userCell.userName, pwdCell.password);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"Loading...";
    
    UserModel *user = [[UserModel alloc] init];
    user.userName = userCell.userName;
    user.password = pwdCell.password;
    
    HTTPManager *manager = [HTTPManager manager];
    [manager login:user Success:^(NSDictionary *responseObject) {
        [hud hide:YES];
        user.email = responseObject[@"email"];
        user.firstName = responseObject[@"firstName"];
        user.lastName = responseObject[@"lastName"];
#warning 后续需要getUserInfo接口
        [UserDefaultDataHelper storeData:user.email WithKey:UserDefaultKeyUserEmail];
        [UserDefaultDataHelper storeData:user.userName WithKey:UserDefaultKeyUserUserName];
        [UserDefaultDataHelper storeData:user.firstName WithKey:UserDefaultKeyUserfirstName];
        [UserDefaultDataHelper storeData:user.lastName WithKey:UserDefaultKeyUserlastName];
        
        BookingViewController *mainVC = [[BookingViewController alloc] init];
        [self.navigationController pushViewController:mainVC animated:YES];
    } failure:^(NSError *error) {
        [hud hide:YES];
        MBProgressHUD *errorHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        errorHud.labelText = @"Wrong Username OR Password";
        errorHud.mode = MBProgressHUDModeText;
        [errorHud hide:YES afterDelay:1.f];
    }];

}

-(void)registerAccount:(UIButton *)sender {
    
}

-(void)dismissVC {
    [(UITextField *)[self.tableView viewWithTag:LoginUserNameCellTextFieldTag] resignFirstResponder];
    [(UITextField *)[self.tableView  viewWithTag:LoginPasswordCellTextFieldTag] resignFirstResponder];

    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - layout

-(void)initTableFooterView {
    UIView *footbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 120)];
    footbgView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footbgView;
    
    UIButton *loginBtn    = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.tableView addSubview:loginBtn];
    [self.tableView addSubview:registerBtn];
    
    [loginBtn setTitle:@"Login" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    UIImage *image = [PureColorImageHelper imageWithColor:@"#5dca94" withHeight:44 withWidth:self.tableView.frame.size.width - 30];
    [loginBtn setBackgroundImage:image forState:UIControlStateNormal];
    loginBtn.layer.cornerRadius = 5.f;
    loginBtn.layer.masksToBounds = YES;
    [loginBtn addTarget:self action:@selector(loginAccount:) forControlEvents:UIControlEventTouchUpInside];
    
    [registerBtn setTitle:@"Help" forState:UIControlStateNormal];
    registerBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    //registerBtn.contentVerticalAlignment = NSTextAlignmentCenter;
    [registerBtn setTitleColor:[UIColor colorWithHexString:@"6d6d6d"] forState:UIControlStateNormal];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [registerBtn addTarget:self action:@selector(registerAccount:) forControlEvents:UIControlEventTouchUpInside];
    
    [loginBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footbgView.centerX);
        make.top.equalTo(footbgView.top).offset(20);
        make.width.equalTo(@(image.size.width));
        make.height.equalTo(@(image.size.height));
    }];
    
    [registerBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginBtn.bottom).offset(8);
        make.right.equalTo(loginBtn.right);
        //make.width.equalTo(@80);
        //make.height.equalTo(@22);
    }];
}

@end
